﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace TagBasedResourceManagePlatform.Misc
{
    public class ThumbnailHelper
    {
        public static readonly Size PreferThumbnailSize = new Size(256, 256);

        public static bool Generate(string srcPath, System.IO.Stream destStream, System.Drawing.Size thumbnailSize)
        {
            if(srcPath==null)
                throw new ArgumentNullException("srcPath");
            if (destStream == null)
                throw new ArgumentNullException("destStream");

            string[] mineType = MineTypeHelper.GetMineTypeString(System.IO.Path.GetExtension(srcPath)).Split('/');

            switch (mineType[0])
            {
                case "image":
                    switch (mineType[1])
                    {
                        case "jpeg":
                        case "png":
                        case "bmp":
                        case "tiff":
                        case "gif":
                            return GenerateCommonImage(srcPath, destStream, thumbnailSize);
                    }
                    return false;
                default:
                    return false;
            }
        }

        private static bool GenerateCommonImage(string srcPath,System.IO.Stream dest,System.Drawing.Size thumbnailSize)
        {
            Image srcImage = Image.FromFile(srcPath);
            Bitmap destImage = new Bitmap(thumbnailSize.Width, thumbnailSize.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            using(Graphics g = Graphics.FromImage(destImage))
            {
                float srcRadio = (srcImage.Height + 0.0f) / (srcImage.Width + 0.0f);
                float destRaido = (thumbnailSize.Height + 0.0f) / (thumbnailSize.Width + 0.0f);
                float targetH, targetW, targetX, targetY;

                if (srcRadio > destRaido)
                {
                    targetH = thumbnailSize.Height;
                    targetW = targetH / srcRadio;
                }
                else
                {
                    targetW = thumbnailSize.Width;
                    targetH = targetW * srcRadio;
                }

                targetX = (thumbnailSize.Width - targetW) * 0.5f;
                targetY = (thumbnailSize.Height - targetH) * 0.5f;

                g.Clear(Color.White);
                g.DrawImage(srcImage, new RectangleF(targetX, targetY, targetW, targetH), new RectangleF(0f, 0f, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel);
            }

            destImage.Save(dest, System.Drawing.Imaging.ImageFormat.Jpeg);

            //Reset position for target stream.
            dest.Position = 0;

            return true; 
        }

    }
}
